package com.hxh.learn.config;

import com.hxh.learn.model.SysUser;
import com.hxh.learn.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: hxh
 * @Date: 2023/3/3
 */
@Service
public class LoginUserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private ISysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //根据用户名查询用户
        SysUser user=userService.getByName(userName);
        if (user==null){
            throw new RuntimeException("用户名不存在");
        }
        return new User(user.getUsername(),user.getPassword(),getUserAuths());
    }

    private List<GrantedAuthority> getUserAuths() {
        return AuthorityUtils.commaSeparatedStringToAuthorityList("add,update");
    }
}
